package com.qingzhu;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class CorsServer implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        request.setCharacterEncoding("utf-8");
//        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        // 动态获取请求的地址(可以放行所有的请求)
        String origin = request.getHeader("Origin");
        // 允许跨域
        response.setHeader("Access-Control-Allow-Origin",origin);
        // 允许携带cookie访问服务器
        response.setHeader("Access-Control-Allow-Credentials","true");
        /* 说明：
         * 'Content-Type' 因为在发送的请求中是一个application/json类型，而默认情况不包含该MIME类型，所以需要额外设置
         * 'token' 自定义的头部信息token，用来替代cookie
         * 'user'  用来携带用户信息 */
        response.setHeader("Access-Control-Allow-Headers","Content-Type,token,user");

        System.out.println("动态地址:"+origin);
        filterChain.doFilter(request,response);
    }

    @Override
    public void destroy() {

    }
}
